package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.IntegralChange;
import cn.wolfcode.trip.base.domain.Sign;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.IntegralChangeMapper;
import cn.wolfcode.trip.base.mapper.IntegralMapper;
import cn.wolfcode.trip.base.mapper.SignMapper;
import cn.wolfcode.trip.base.service.ISignService;
import cn.wolfcode.trip.base.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 签到实现
 */
@Service
public class ISignServiceImpl implements ISignService {
    @Autowired
    private SignMapper signMapper;
    @Override
    public Sign sign(User u) throws Exception {
        //1.根据id,去签到表查询当天数据,如果有签到,抛出异常--重复签到
        Long userId = u.getId();
        Sign sign = signMapper.getSignByUserId(u.getId(), DateUtil.formatDate(new Date()));
        System.out.println(new Date());
        if (sign != null) {
            throw new Exception("亲,今天已签到,请明日再来~");
        }
        //2.如果未签到
        //2.0根据id查询(当月需求待开发)累计签到总次数
        int count = signMapper.selectSignCount(userId);
        //2.1.查询昨天签到情况
        //2.2.根据昨天是否签到,增加连续签到次数
        //获取昨天时间
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        sign = signMapper.getSignByUserId(userId, DateUtil.formatDate(cal.getTime()));
        if (sign == null) {
            sign = new Sign();
            sign.setSigncount(1);
        } else {
            sign.setSigncount(sign.getSigncount() + 1);

        }
        //进行签到
        sign.setUser(u);
        sign.setCount(count + 1);
        sign.setSignTime(new Date());
        signMapper.insert(sign);
        return sign;
    }
}
